<?php

namespace app\system\middleware;

use app\system\logic\User;
use common\ApiReturn;
use think\Request;

class ApiAuth
{
    /**
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        if (User::uuid() == 1) {
            return $next($request);
        }

        // 个人中心的权限属于登录用户的，任何信息都可查看
        if ($request->controller() === 'UserCenter') {
            return $next($request);
        }

        // 快速操作数据的验证
        $user_auth_list = User::getAuth();
        if (preg_match('/^[\w]+$/', $request->pathinfo())) {
            $path_info = preg_replace('/_/', '/', $request->pathinfo()) . '/' . strtolower($request->method());
            if (empty($user_auth_list) || !in_array($path_info, $user_auth_list)) {
                return ApiReturn::error('尚未获取权限 【' . $path_info . '】', null, AUTHORIZE_FORBID);
            }
        }

        return $next($request);
    }
}

;